package com.mymarkdown.app.fx.event.hander.impl;

import cn.hutool.core.io.IoUtil;
import com.mymarkdown.app.fx.annotation.KeyWord;
import com.mymarkdown.app.fx.enums.FxEventEnum;
import com.mymarkdown.app.fx.event.hander.KeyWordHandler;
import com.mymarkdown.app.fx.event.hander.MenuHandler;
import com.mymarkdown.app.fx.event.model.FxEvent;
import com.mymarkdown.app.interfaces.UserInfoService;
import com.mymarkdown.app.util.FileChooserUtil;
import com.mymarkdown.app.util.TemplateHtmlUtil;
import com.mymarkdown.app.util.ThreadPool;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.websocket.interfaces.WebSocketSendMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;
import javafx.scene.web.WebEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;

/**
 * @author zenglun
 * @date 2021/12/8 8:32 上午
 * @description: 将Md文件导出为HTML
 */
@Slf4j
@KeyWord(FxEventEnum.EXPORT_MD_HTML)
@Component
public class ExportMdToHtmlMenuHandlerImpl implements MenuHandler, KeyWordHandler {

    @Autowired
    private CacheManager cacheManager;

    private Cache cache;

    @Autowired
    private WebSocketSendMessage webSocketSendMessage;

    @Autowired
    private UserInfoService userInfoService;

    @PostConstruct
    public void init() {
        cache = cacheManager.getCache("cacheMarkdownHtmlTemplate");
    }

    @Override
    public void handler(WebEngine engine, FxEvent event) {
        //下发指令通知客户端
        webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.GET_MD_TO_HTML.getMessageType()));

        //弹出对话框要用户进行选择，
        FileChooserUtil.showSaveDialog(file -> {

            BlockingQueue<File> operationMdPdfFile = userInfoService.getOperationMdPdfFile();

            try {
                File operationPdfFile = operationMdPdfFile.peek();

                if (!Objects.isNull(operationPdfFile)) {
                    operationMdPdfFile.clear();
                }

                operationMdPdfFile.put(file);
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error("[ExportMdPdfMenuHandlerImpl]---[handler],保存当前要保存的PDF文档发生中断,异常信息为:{}", e);
            }
        }, "html", "*.html", "*.htm");
        //开启一个线程保存数据
        ThreadPool.getInstant().commit(() -> {
            //获取操作的html内容
            try {
                BlockingQueue<String> operationMdHTML = userInfoService.getOperationMdHTML();

                String html = operationMdHTML.take();

                BlockingQueue<File> operationMdPdfFile = userInfoService.getOperationMdPdfFile();

                File take = operationMdPdfFile.take();

                //读取模板字符串

                html = TemplateHtmlUtil.getSelf().getTemplateStr() + html + "</div></body></html>";

                //将读取到的html写入流中
                IoUtil.write(new FileOutputStream(take), true, html.getBytes(StandardCharsets.UTF_8));

                //写完之后发送信息
                webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType()).setBody("导出成功!"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                log.error("[ExportMdToHtmlMenuHandlerImpl]---[handler]，导入Html文件失败,未找到相关创建文件,异常信息为:{}", e);
                webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType()).setBody("导入失败,未找到相关创建文件!"));
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error("[ExportMdPdfMenuHandlerImpl]---[handler],等待客户端上传HTML发生中断,异常信息为:{}", e);
            }
        });
    }

    @Override
    public boolean afterHandler(WebEngine engine, FxEvent event) {
        return true;
    }

    @Override
    public void beforeHandler(WebEngine engine, FxEvent event) {

    }
}
